<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>实时聊天测试</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .chat-container {
            width: 90%;
            max-width: 1200px;
            height: 80vh;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
            display: flex;
        }

        .sidebar {
            width: 300px;
            background: #f8f9fa;
            border-right: 1px solid #e9ecef;
            display: flex;
            flex-direction: column;
        }

        .sidebar-header {
            padding: 20px;
            background: #007bff;
            color: white;
            text-align: center;
        }

        .sidebar-header h2 {
            margin: 0;
            font-size: 1.5em;
        }

        .user-info {
            padding: 15px;
            background: #e9ecef;
            border-bottom: 1px solid #dee2e6;
        }

        .user-info input {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #ced4da;
            border-radius: 20px;
            font-size: 14px;
        }

        .online-users {
            flex: 1;
            overflow-y: auto;
            padding: 15px;
        }

        .user-item {
            padding: 10px;
            margin: 5px 0;
            background: white;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s;
            border-left: 4px solid #007bff;
        }

        .user-item:hover {
            background: #e3f2fd;
            transform: translateX(5px);
        }

        .user-item.online {
            border-left-color: #28a745;
        }

        .user-item.offline {
            border-left-color: #6c757d;
            opacity: 0.6;
        }

        .main-chat {
            flex: 1;
            display: flex;
            flex-direction: column;
        }

        .chat-header {
            padding: 20px;
            background: #007bff;
            color: white;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .chat-title {
            font-size: 1.3em;
            font-weight: 600;
        }

        .connection-status {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .status-dot {
            width: 10px;
            height: 10px;
            border-radius: 50%;
        }

        .status-dot.connected {
            background: #28a745;
            animation: pulse 2s infinite;
        }

        .status-dot.disconnected {
            background: #dc3545;
        }

        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }

        .messages-container {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            background: #f8f9fa;
        }

        .message {
            margin-bottom: 15px;
            max-width: 70%;
            animation: fadeIn 0.3s;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .message.sent {
            align-self: flex-end;
            margin-left: auto;
        }

        .message.received {
            align-self: flex-start;
        }

        .message-bubble {
            padding: 12px 16px;
            border-radius: 18px;
            position: relative;
            word-wrap: break-word;
        }

        .sent .message-bubble {
            background: #007bff;
            color: white;
            border-bottom-right-radius: 5px;
        }

        .received .message-bubble {
            background: white;
            color: #333;
            border: 1px solid #e9ecef;
            border-bottom-left-radius: 5px;
        }

        .message-sender {
            font-size: 0.8em;
            margin-bottom: 5px;
            font-weight: 600;
        }

        .message-time {
            font-size: 0.7em;
            opacity: 0.7;
            margin-top: 5px;
            text-align: right;
        }

        .typing-indicator {
            padding: 10px 20px;
            font-style: italic;
            color: #6c757d;
            display: none;
        }

        .input-area {
            padding: 20px;
            background: white;
            border-top: 1px solid #e9ecef;
        }

        .input-group {
            display: flex;
            gap: 10px;
            align-items: flex-end;
        }

        .message-input {
            flex: 1;
            padding: 12px 16px;
            border: 1px solid #ced4da;
            border-radius: 25px;
            font-size: 14px;
            resize: none;
            max-height: 120px;
            outline: none;
            transition: border-color 0.3s;
        }

        .message-input:focus {
            border-color: #007bff;
            box-shadow: 0 0 0 0.2rem rgba(0,123,255,.25);
        }

        .send-button {
            background: #007bff;
            color: white;
            border: none;
            border-radius: 50%;
            width: 45px;
            height: 45px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s;
        }

        .send-button:hover {
            background: #0056b3;
            transform: scale(1.05);
        }

        .send-button:disabled {
            background: #6c757d;
            cursor: not-allowed;
            transform: none;
        }

        .status-indicator {
            font-size: 0.8em;
            color: #6c757d;
            text-align: center;
            margin-top: 10px;
        }

        .system-message {
            text-align: center;
            color: #6c757d;
            font-style: italic;
            margin: 10px 0;
            font-size: 0.9em;
        }

        .welcome-message {
            text-align: center;
            margin: 20px 0;
            color: #6c757d;
        }

        .emoji-button {
            background: none;
            border: none;
            font-size: 1.2em;
            cursor: pointer;
            padding: 10px;
            border-radius: 50%;
            transition: background 0.3s;
        }

        .emoji-button:hover {
            background: #e9ecef;
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <!-- 侧边栏 -->
        <div class="sidebar">
            <div class="sidebar-header">
                <h2>实时聊天</h2>
            </div>
            
            <div class="user-info">
                <input type="text" id="username-input" placeholder="输入您的用户名..." />
            </div>

            <div class="online-users">
                <h3 style="margin-bottom: 15px; color: #495057;">在线用户</h3>
                <div id="users-list"></div>
            </div>
        </div>

        <!-- 主聊天区域 -->
        <div class="main-chat">
            <div class="chat-header">
                <div class="chat-title">
                    <span id="current-chat-target">群聊</span>
                </div>
                <div class="connection-status">
                    <span id="status-text">连接中...</span>
                    <div id="status-dot" class="status-dot disconnected"></div>
                </div>
            </div>

            <div class="messages-container" id="messages">
                <div class="welcome-message">
                    <h3>欢迎使用实时聊天功能！</h3>
                    <p>请输入用户名开始聊天</p>
                </div>
            </div>

            <div class="typing-indicator" id="typing-indicator"></div>

            <div class="input-area">
                <div class="input-group">
                    <textarea 
                        id="message-input" 
                        class="message-input" 
                        placeholder="输入消息..." 
                        rows="1"
                        disabled
                    ></textarea>
                    <button class="emoji-button" onclick="toggleEmojiPicker()">表情</button>
                    <button id="send-button" class="send-button" disabled>
                        <svg width="20" height="20" viewBox="0 0 24 24">
                            <path fill="currentColor" d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
                        </svg>
                    </button>
                </div>
                <div class="status-indicator" id="connection-status">正在连接 WebSocket...</div>
            </div>
        </div>
    </div>

	<th:block th:insert="~{include :: footer}" />
    <script src="/js/sockjs/sockjs.min.js"></script>
    <script src="/js/sockjs/stomp.min.js"></script>
    <script>
        // 全局变量
        let stompClient = null;
        let currentUser = null;
        let typingTimer = null;
        let isConnected = false;

        // 初始化连接
        function connect() {
            const socket = new SockJS('/ws');
            stompClient = Stomp.over(socket);
            
            stompClient.connect({}, function(frame) {
                console.log('WebSocket 连接成功:', frame);
                isConnected = true;
                updateConnectionStatus(true);
                
                // 订阅测试公共频道
                stompClient.subscribe('/topic/test/public', function(message) {
                    const msg = JSON.parse(message.body);
                    displayMessage(msg);
                });

                // 订阅用户加入/离开通知
                stompClient.subscribe('/topic/test/user.status', function(message) {
                    const userStatus = JSON.parse(message.body);
                    updateUserStatus(userStatus);
                });

                // 订阅输入状态
                stompClient.subscribe('/topic/test/typing', function(message) {
                    const typingInfo = JSON.parse(message.body);
                    showTypingIndicator(typingInfo);
                });

                // 发送用户上线通知
                if (currentUser) {
                    stompClient.send('/app/test/user.join', {}, JSON.stringify({
                        username: currentUser,
                        status: 'online'
                    }));
                }

            }, function(error) {
                console.error('WebSocket 连接失败:', error);
                isConnected = false;
                updateConnectionStatus(false);
                
                // 5秒后重试
                setTimeout(connect, 5000);
            });
        }

        // 更新连接状态显示
        function updateConnectionStatus(connected) {
            const statusDot = document.getElementById('status-dot');
            const statusText = document.getElementById('status-text');
            const connectionStatus = document.getElementById('connection-status');
            
            if (connected) {
                statusDot.className = 'status-dot connected';
                statusText.textContent = '已连接';
                connectionStatus.textContent = '连接成功';
                connectionStatus.style.color = '#28a745';
            } else {
                statusDot.className = 'status-dot disconnected';
                statusText.textContent = '连接断开';
                connectionStatus.textContent = '连接失败，正在重连...';
                connectionStatus.style.color = '#dc3545';
            }
        }

        // 用户名设置
        document.getElementById('username-input').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                const username = this.value.trim();
                if (username) {
                    setUsername(username);
                }
            }
        });

        function setUsername(username) {
            currentUser = username;
            document.getElementById('username-input').disabled = true;
            document.getElementById('message-input').disabled = false;
            document.getElementById('send-button').disabled = false;
            
            // 清除欢迎消息
            document.querySelector('.welcome-message').style.display = 'none';
            
            // 添加系统消息
            addSystemMessage(`欢迎 ${username} 加入聊天！`);
            
            // 发送上线通知
            if (isConnected && stompClient) {
                stompClient.send('/app/test/user.join', {}, JSON.stringify({
                    username: username,
                    status: 'online'
                }));
            }
        }

        // 发送消息
        document.getElementById('send-button').addEventListener('click', sendMessage);
        
        document.getElementById('message-input').addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            } else {
                // 检测输入状态
                handleTyping();
            }
        });

        function sendMessage() {
            const messageInput = document.getElementById('message-input');
            const message = messageInput.value.trim();
            
            if (!message || !currentUser || !isConnected || !stompClient) {
                return;
            }

            const chatMessage = {
                fromUser: currentUser,
                content: message,
                timestamp: new Date().toISOString(),
                messageType: 1 // 文本消息
            };

            stompClient.send('/app/test/chat.send', {}, JSON.stringify(chatMessage));
            messageInput.value = '';
            
            // 清除输入状态
            clearTyping();
        }

        // 处理输入状态
        function handleTyping() {
            if (!currentUser || !isConnected || !stompClient) return;
            
            clearTimeout(typingTimer);
            
            // 发送输入状态
            stompClient.send('/app/test/chat.typing', {}, JSON.stringify({
                username: currentUser,
                isTyping: true
            }));
            
            // 3秒后自动清除输入状态
            typingTimer = setTimeout(() => {
                clearTyping();
            }, 3000);
        }

        function clearTyping() {
            if (stompClient && currentUser) {
                stompClient.send('/app/test/chat.typing', {}, JSON.stringify({
                    username: currentUser,
                    isTyping: false
                }));
            }
            
            clearTimeout(typingTimer);
            typingTimer = null;
        }

        // 显示输入指示器
        function showTypingIndicator(typingInfo) {
            if (typingInfo.username === currentUser) return;
            
            const indicator = document.getElementById('typing-indicator');
            
            if (typingInfo.isTyping) {
                indicator.textContent = `${typingInfo.username} 正在输入...`;
                indicator.style.display = 'block';
            } else {
                indicator.style.display = 'none';
            }
        }

        // 显示消息
        function displayMessage(message) {
            const messagesContainer = document.getElementById('messages');
            const isCurrentUser = message.fromUser === currentUser;
            
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${isCurrentUser ? 'sent' : 'received'}`;
            
            messageDiv.innerHTML = `
                <div class="message-bubble">
                    <div class="message-sender">${message.fromUser}</div>
                    <div>${escapeHtml(message.content)}</div>
                    <div class="message-time">${formatTime(message.timestamp)}</div>
                </div>
            `;
            
            messagesContainer.appendChild(messageDiv);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }

        // 添加系统消息
        function addSystemMessage(text) {
            const messagesContainer = document.getElementById('messages');
            const systemDiv = document.createElement('div');
            systemDiv.className = 'system-message';
            systemDiv.textContent = text;
            messagesContainer.appendChild(systemDiv);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }

        // 更新用户状态
        function updateUserStatus(userStatus) {
            const usersList = document.getElementById('users-list');
            
            // 简单的用户列表管理
            // 在实际应用中，这里应该维护一个用户列表并更新状态
            if (userStatus.status === 'online') {
                addSystemMessage(`${userStatus.username} 加入了聊天`);
            } else if (userStatus.status === 'offline') {
                addSystemMessage(`${userStatus.username} 离开了聊天`);
            }
        }

        // 工具函数
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        function formatTime(timestamp) {
            const date = new Date(timestamp);
            return date.toLocaleTimeString('zh-CN', {
                hour: '2-digit',
                minute: '2-digit'
            });
        }

        // 简单的表情选择器
        function toggleEmojiPicker() {
            const emojis = ['[微笑]', '[大笑]', '[喜欢]', '[酷]', '[赞]', '[心]', '[庆祝]', '[火]'];
            const messageInput = document.getElementById('message-input');
            
            // 简单的实现，实际应用中可以使用更复杂的表情选择器
            const emoji = emojis[Math.floor(Math.random() * emojis.length)];
            messageInput.value += emoji;
            messageInput.focus();
        }

        // 自适应输入框高度
        document.getElementById('message-input').addEventListener('input', function() {
            this.style.height = 'auto';
            this.style.height = Math.min(this.scrollHeight, 120) + 'px';
        });

        // 页面加载时连接
        window.addEventListener('load', function() {
            connect();
        });

        // 页面卸载时断开连接
        window.addEventListener('beforeunload', function() {
            if (stompClient && currentUser) {
                stompClient.send('/app/test/user.leave', {}, JSON.stringify({
                    username: currentUser,
                    status: 'offline'
                }));
            }
            
            if (stompClient) {
                stompClient.disconnect();
            }
        });
    </script>
</body>
</html>